package com.mmall.concurrency.AQS;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CycliBarrierDemo {

    private static int threadNum;
    // 等待的线程数够5个就执行
    static CyclicBarrier cyclicBarrier = new CyclicBarrier(5,
            () ->{log.info("====running"); });

    public static void main(String[] args) throws Exception {

        //线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i< 10; i++){
            final int threadNum = i;
            Thread.sleep(1000); //执行前睡一会
            executorService.execute( () -> {
                try{
                    race(threadNum);
                }catch (Exception e){
                    log.error("race error :",e);
                }
            });
        }
        executorService.shutdown();
    }

    public static void race(int threadNum) throws Exception{
        Thread.sleep(1000);
        log.info("{} is ready.", threadNum);
        try{
            // cyclicBarrier.await(1000, TimeUnit.MILLISECONDS);
            cyclicBarrier.await();
        }catch (Exception e){
            log.warn("===============出错？别出来", "hahaha");
        }
        log.info("{} is continue.", threadNum);

    }

}
